// main.cpp
#include "raylib.h"
#include "font_manager.h"
#include "BoardManager.h"
#include "Player.h"
#include "ConfigManager.h"
#include <cstdlib>
#include <ctime>
#include <string>
#include <iostream>

int main() {
    // 初始化游戏配置
    GameConfig config = ConfigManager::LoadConfig();
    
    // 输出配置信息
    std::cout << "使用默认配置." << std::endl;
    std::cout << "Board type probabilities:" << std::endl;
    for (const auto& pair : config.boardTypeProbabilities) {
        std::cout << "  " << pair.first << ": " << pair.second << std::endl;
    }
    
    // 初始化窗口和系统
    InitWindow(config.screenWidth, config.screenHeight, "Downdown Game");
    SetTargetFPS(60);
    
    // 初始化游戏对象
    Player player(config.screenWidth / 2, 100, config);
    BoardManager boardManager;
    boardManager.Init(config);
    
    // 游戏主循环
    bool gameOver = false;
    int frameCounter = 0;
    
    while (!WindowShouldClose() && !gameOver) {
        // 更新游戏状态
        player.Update();
        
        // 更新板子
        boardManager.Update();
        
        // 获取活跃板子列表
        std::vector<Board*> activeBoards = boardManager.GetActiveBoards();
        
        // 检测玩家与板子的碰撞
        Rectangle playerRect = player.GetRect();
        for (Board* board : activeBoards) {
            if (board->CheckCollision(playerRect)) {
                // 根据板子类型处理碰撞
                if (board->GetType() == "SpikyBoard") {
                    player.HandleSpikyBoardCollision(board->GetPosition().y);
                } else if (board->IsBreakable()) {
                    player.HandleBreakableBoardCollision(board->GetPosition().y);
                } else {
                    player.HandleBoardCollision(board->GetPosition().y);
                }
                board->OnPlayerLand();
            }
        }
        
        frameCounter++;
        // 每30帧检查一次游戏结束条件
        if (frameCounter % 30 == 0) {
            Vector2 playerPos = player.GetPosition();
            Vector2 playerSize = player.GetSize();
            
            // 玩家位置超出屏幕底部、移出屏幕上方、到达屏幕顶部或死亡时结束游戏
            if (playerPos.y > config.screenHeight + playerSize.y || 
                playerPos.y < -playerSize.y ||
                playerPos.y <= 0 ||
                !player.IsAlive()) {
                gameOver = true;
                // 检查并更新最高分
                if (player.GetCurrentScore() > player.GetHighScore()) {
                    player.SetHighScore(player.GetCurrentScore());
                    player.SaveHighScore();
                }
            }
        }
        
        // 绘制游戏画面
        BeginDrawing();
        ClearBackground(RAYWHITE);
        
        // 绘制板子
        boardManager.Draw();
        
        // 绘制玩家
        player.Draw();
        
        EndDrawing();
    }
    
    // 关闭窗口
    CloseWindow();
    return 0;
}